package dao

import (
    "github.com/jinzhu/gorm"
    "gonaio_base/service"
    "gonaio_user_service/model"
)

type User struct {
}

var userInstance = new(User)

func NewUser() *User {
    return userInstance
}

func init() {
    m := NewUser()
    db, _ := m.GetDB()
    db.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(m.GetModel())
}

func (*User) GetModel() (result *model.User) {
    result = &model.User{}
    return
}

func (that *User) GetDB() (db *gorm.DB, err error) {
    m := that.GetModel()
    db, err = bservice.New().GetDB(m.Alias())
    return
}

func (that *User) ListData(page, limit int64) (list []model.User, count int64, err error) {
    db, _ := that.GetDB()
    offset := (page - 1) * limit
    err = db.Model(that.GetModel()).Count(&count).Offset(offset).Limit(limit).Find(&list).Error
    return
}

func (that *User) GetUserByUsername(username string) (m model.User, err error) {
    db, _ := that.GetDB()
    err = db.Model(that.GetModel()).Where("username=?", username).First(&m).Error
    return
}

func (that *User) Reg(username, password string) (err error) {
    m := that.GetModel()
    m.Username = username
    m.Password = password
    db, _ := that.GetDB()
    db.Create(m)
    return
}
